#!/usr/bin/env bash

set -eux

# Change directory to repository root.
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
readonly SCRIPT_DIR
cd "${SCRIPT_DIR}/.."

TIMESTAMP=$(date --iso-8601=minutes | sed 's/://g' | sed 's/+0000/Z/g')
export DB_PATH="data/store.db"
export DB_COPY_PATH="data/${TIMESTAMP}.db"

./dev-scripts/reset-db

set +x
# shellcheck disable=SC1091
. .env.prod
set -x

export LITESTREAM_REGION
export DB_REPLICA_URL
export LITESTREAM_ACCESS_KEY_ID
export LITESTREAM_SECRET_ACCESS_KEY

# Export DB_PATH so that litestream uses the variable to populate
# litestream.yml.
export DB_PATH

litestream snapshots -config litestream.yml "${DB_PATH}"

# Retrieve live DB
litestream restore -config litestream.yml -o "${DB_COPY_PATH}" "${DB_PATH}"
cp "${DB_COPY_PATH}" "${DB_PATH}"
